#!/bin/sh



#Usage: ./rpm_test.sh rpm_path

#docker内部的脚本
test_sh=test_in_docker.sh
#获取当前路径
now_path=$(dirname $(readlink -f $test_sh))
#rpm测试成功，保存log
test_save=$now_path/success_test
if [ ! -d $test_save ];then
	mkdir $test_save
fi 


#rpm的test的操作
rpm_test()
{
	#获取输入的rpm路径
	rpm_path=$1 
	#echo "${rpm_path}"
	
	#搜索此目录下所有的rpm文件
	rpm_files=$(find "${rpm_path}" -type f -name "*.rpm" | grep -v '.src.rpm')
	#echo "${rpm_files}"
	
	#记录rpm的数量
	local num=0 
	
	#循环处理每个rpm 包括
	#install
	#service
	#--help
	#remove
	for file in ${rpm_files}
	do
		num=$(($num+1))
		echo -e "==================================== ${num} rpm start test ============================================="
		
		#获取rpm文件名
		file_name=${file##*/}
		echo -e "RPM: ${file_name}\n"
		
		
		#清除缓存容器
		docker inspect rpm_${num} -f '{{.Name}}' > /dev/null 2>&1
		if [ $? -eq 0 ];then
			if [ docker inspect --format '{{.State.Running}}' rpm_${num} ];then
				docker stop rpm_${num}
			fi
			docker rm -f rpm_${num}
		fi
		#启动docker
		docker run -itd --privileged=true --name rpm_${num} openeuler:rpm /usr/sbin/init
		
		#拷贝文件
		docker cp $file rpm_${num}:/root/
		docker cp $test_sh rpm_${num}:/root/
		
		echo -e "Start $num rpm test in rpm_${num} container ........."
		
		#docker内部测试
		docker exec -it rpm_${num} bash -c " chmod a+x /root/$test_sh "
		
		docker exec -it rpm_${num} bash -c "cd /root && source $test_sh"
		
		
		#判断测试结果
		if [ $? -eq 0 ];then
			echo -e "Test ${file} end !!!"	
		else
			echo -e "Test ${file} has some error !!!"	
		fi
			
		#删除docker
		echo -e "Stop and Delete rpm_${num} container ........."
		if [ $(docker inspect --format '{{.State.Running}}' rpm_${num}) ];then
			docker stop rpm_${num}
		fi
		docker rm -f rpm_${num}

	done
}


rpm_test "$1" | tee $test_save/rpm_test.log
